package org.dlow.invoke;

import org.dlow.common.Cache;
import org.dlow.utils.ServiceNameBuilder;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @Author: 山沐与山
 * @CreateTime: 2024-05-10 16:54
 */
public class JdkReflectionExecutor implements MethodExecutor{

    private Map<Integer,MethodInvocation> methodCache = new HashMap<>();

    @Override
    public Object execute(Invocation invocation) throws Exception {
        final Integer methodCode = invocation.getMethodCode();
        if (!methodCache.containsKey(methodCode)) {
            final String key = ServiceNameBuilder.buildServiceKey(invocation.getClassName(), invocation.getServiceVersion());
            Object bean = Cache.SERVICE_MAP.get(key);
            final Class<?> aClass = bean.getClass();

            final Method method = aClass.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            methodCache.put(methodCode,new MethodInvocation(bean,method));
        }
        final MethodInvocation methodInvocation = methodCache.get(methodCode);
        return methodInvocation.execute(invocation.getParameter());
    }
}
